<div id="AddResource" class="modal fade">
  <div class="modal-dialog">
    <div class="modal-content">
      <div class="modal-header">
        <button type="button" class="close" data-dismiss="modal">&times;</button>
        <%= render partial: 'help/help_resource_new' %>
        <h4><%= t('document.main_title')%></h4>
      </div>
      <div class="modal-body">


        <div class="layoutform">
          <!-- Tags preloaded -->
          <%@tags = ActivityObject.tag_counts(:limit => 100, :order => "count desc")%>
          <ul id="resourcePreloadTagList" style="display:none">
            <%@tags.each do |tag| %>
              <li><%=tag.name%></li>
            <%end%>
          </ul>

          <p><%= t('document.body.title1')%></p>
          <hr>

          <div class="panel-group" id="accordion1" role="tablist" aria-multiselectable="true">
            <div class="panel panel-default">
              <div class="panel-heading" role="tab" id="headingOne">
                <h4 class="panel-title">
                  <a class="accordion-toggle" data-toggle="collapse" data-parent="#accordion1" href="#document" aria-expanded="true" aria-controls="document">
                    <i class="fa fa-folder-open"></i> <%= t('document.options.documents')%>
                  </a>
                </h4>
              </div>
              <div id="document" class="panel panel-collapse collapse in" role="tabpanel" aria-labelledby="headingOne">
                <div class="panel-body">
                  <% d = Document.new %>
                  <% d.owner_id = Actor.normalize_id(current_subject) %>
                  <%= form_for d, :namespace => 'new_file_only', :html => { :multipart => true }, :remote => false do |f| %>
                    <%= f.hidden_field :owner_id %>
                    <%= f.file_field :file %>
                    <%= f.hidden_field :title%>
                    <%= f.hidden_field :description%>
                    <%= f.hidden_field :tag_list, :multiple => true %>
                    <%= f.hidden_field :language, :value => "" %>
                    <%= f.hidden_field :license_id %>
                    <%= f.hidden_field :original_author %>
                    <%= f.hidden_field :license_attribution %>
                    <%= f.hidden_field :license_custom %>
                    <%= f.hidden_field :age_min, :value => "0" %>
                    <%= f.hidden_field :age_max, :value => "0" %>
                    <%= f.submit t('button.save'), :class => "document hide"%>
                  <% end %>
                </div>
              </div>
            </div>

            <div class="panel panel-default">
              <div class="panel-heading" role="tab" id="headingTwo">
                <h4 class="panel-title">
                  <a class="accordion-toggle" data-toggle="collapse" data-parent="#accordion1" href="#link" aria-expanded="false" aria-controls="link">
                    <i class="fa fa-link"></i> <%= t('document.options.links')%>
                  </a>
                </h4>
              </div>
              <div id="link" class="panel panel-collapse collapse" role="tabpanel" aria-labelledby="headingTwo">
                <div class="panel-body">

                  <% d = Link.new %>
                  <% d.owner_id = Actor.normalize_id(current_subject) %>
                  <%= form_for d, :namespace => 'new_file_only', :html => { :multipart => true }, :remote => false do |f| %>
                    <%= f.hidden_field :owner_id %>
                    <%= f.hidden_field :callback_url %>
                    <%= f.hidden_field :loaded %>
                    <%= f.text_field :url %>
                    <%= f.hidden_field :title%>
                    <%= f.hidden_field :description%>
                    <%= f.hidden_field :tag_list, :multiple => true %>
                    <%= f.hidden_field :language, :value => "" %>
                    <%= f.hidden_field :license_id %>
                    <%= f.hidden_field :original_author %>
                    <%= f.hidden_field :license_attribution %>
                    <%= f.hidden_field :license_custom %>
                    <%= f.hidden_field :age_min, :value => "0" %>
                    <%= f.hidden_field :age_max, :value => "0" %>
                    <%= f.submit t('button.save'), :class => "link hide"%>
                  <% end %>
                </div>
              </div>
            </div>
            <div class="panel panel-default">
              <div class="panel-heading" role="tab" id="headingThree">
                <h4 class="panel-title">
                  <a class="accordion-toggle" data-toggle="collapse" data-parent="#accordion1" href="#embed" aria-expanded="false" aria-controls="embed">
                    <i class="fa fa-code"></i> <%= t('document.options.embed') %>
                  </a>
                </h4>
              </div>
              <div id="embed" class="panel panel-collapse collapse" role="tabpanel" aria-labelledby="headingThree">
                <div class="panel-body">
                  <% d = Embed.new %>
                  <% d.owner_id = Actor.normalize_id(current_subject) %>
                  <%= form_for d, :namespace => 'new_file_only', :html => { :multipart => true }, :remote => false do |f| %>
                    <%= f.hidden_field :owner_id %>
                    <%= f.text_field :fulltext %>
                    <%= f.hidden_field :title%>
                    <%= f.hidden_field :description%>
                    <%= f.hidden_field :tag_list, :multiple => true %>
                    <%= f.hidden_field :language, :value => "" %>
                    <%= f.hidden_field :license_id %>
                    <%= f.hidden_field :original_author %>
                    <%= f.hidden_field :license_attribution %>
                    <%= f.hidden_field :license_custom %>
                    <%= f.hidden_field :age_min, :value => "0" %>
                    <%= f.hidden_field :age_max, :value => "0" %>
                    <%= f.submit t('button.save'), :class => "embed hide"%>
                  <% end %>
                </div>
              </div>
            </div>
          </div>
          
        </div>

        <div class="form-group layoutform">
          <p><%= t('document.body.title2')%></p>
          <hr>
          <div class="resource_info">
            <!--TITULO-->
            <label><%= t('document.leyend.title')%></label>
            <input type="text" class="form-control title" placeholder="<%= t('document.title_input')%>">

            <!--DESCRIPCION-->
            <label><%= t('document.leyend.description')%></label>
            <textarea type="text" rows="6" class="form-control description" placeholder="<%= t('document.input')%>"></textarea>

            <!--TAGS-->
            <label><%= t('document.leyend.tags')%></label>

            <div class="tagBoxDocument">
               <ul class="resourceTagList"></ul>
            </div>

            <div class="clearfloat"></div>

            <!--Avatar-->
            <label class="new_file_avatar_label"><%= t('document.leyend.avatar')%></label>
            <input class="new_file_avatar" type="file" accept="image/*">

            <!--LANGUAGE-->
            <label><%= t('document.leyend.language')%></label>
            <%= select_tag(:language, resource_language_options_for_select(d.language), :class => "resource_language") %>

            <!--AGE SLIDER-->
            <label class="target_age_slider_label"><%= t('document.leyend.recommended_age')%></label>
            <div class="limits">
              <div class="limit1">0</div>
              <div class="limit2">0</div>
            </div>
            <input type="text" class="age-slider" value="" data-slider-min="0" data-slider-max="30" data-slider-step="1" data-slider-value="[0,1]" data-slider-orientation="horizontal" data-slider-tooltip="hide"/>

            <!--LICENSE-->
            <section class="license">
              <br/>
              <label><%= t('document.info.license')%></label>
              <%= select_tag(:license_id, resource_license_options_for_select(d.license_id), :class => "resource_license") %>
              <div class="license_custom_wrapper" style="display:none">
                <label><%=t("document.info.license_custom_form")%>:</label>
                <input type="text" class="form-control title"/>
              </div>
            </section>

            <!--AUTHORSHIP-->
            <section class="authorship">
              <br/>
              <input type="checkbox" checked="checked" class="authorship_checkbox"></input>
              <label class="resource_authorship_label"><%=t("document.leyend.authorship_recognition")%></label>
              <br/>
              <label><%=t("document.info.author")%></label>
              <input type="text" class="form-control title authorship_author" defaultvalue="<%=current_subject.name%>" value="<%=current_subject.name%>" disabled="disabled"/>
              <br/>
              <label><%=t("document.info.license_attribution")%>:</label>
              <input type="text" class="form-control title authorship_attribution" defaultvalue="<%=current_subject.default_license_attribution%>" value="<%=current_subject.default_license_attribution%>" disabled="disabled"/>
            </section>

          </div>
        </div>
      </div>
      <!-- FOOTER -->
      <div class="modal-footer">
        <input type="button" class="btn btn-primary" data-loading-text="<%= t('document.uploading')%>" value="<%= t('document.upload')%>"/>
      </div>
    </div>
  </div>
</div>


<%content_for :javascript do%>

    $('.helpResources').popover({
      html : true,
      content: function() {
        return $('.contentHelpResources').html();
      }
    });


   $("#AddResource").on('shown.bs.modal', function(){
    //SLIDER
    var min = 0;
    var max = 30;
    var step = 1;
    var diff = max - min;

    var positionLimits = function(){
      var value1 = $('#AddResource .age-slider').data('slider').getValue()[0];
      var value2 = $('#AddResource .age-slider').data('slider').getValue()[1];
      $('#AddResource .limit1').text(value1);
      $('#AddResource .limit2').text(value2);

      var percentage =[
        (value1-min)*100/diff,
        (value2-min)*100/diff,
        step*100/diff
      ];

      $("#AddResource .limit1").css("left", function(ev) {
        return $('#AddResource .slider').width() * percentage[0]/100 - $("#AddResource .limit1").width()/2 + 'px';
      });
      $("#AddResource .limit2").css("left", function(ev) {
        return $('#AddResource .slider').width() * percentage[1]/100 - $("#AddResource .limit2").width()/2 + 'px';
      });
    };

    $("#AddResource .age-slider").slider().on('slide', function(ev){
      positionLimits();
    });

    $("#AddResource .age-slider").before($("#AddResource .limits"));
    $('#AddResource .age-slider').data('slider').setValue([0,0]);
    positionLimits();
  });

  //COMMON FIELDS
  var uploadButton = $("#AddResource input[value=<%= t('document.upload')%>][type='button'][class='btn btn-primary']");

  $(uploadButton).click(function(event){
    var resource_type = $("#AddResource .panel.collapse.in").attr('id');

    //Common validation
    if(typeof resource_type != "string"){
      return alert("<%= t('document.body.title3')%>");
    }
    if($(".title").val() == "") {
      return alert("<%= t('document.title_alert')%>");
    }

    switch(resource_type){
      case "document":
        if($("#AddResource input[name='"+resource_type+"[file]']").val() == ""){
          return alert("<%= t('document.body.title3')%>");
        }

        //License validation
        if($("#AddResource section.license select.resource_license").find(":selected").text()==="<%=t("licenses.other")%>"){
          if($("#AddResource section.license div.license_custom_wrapper input").val().trim() == ""){
            return alert('<%=t('document.validation.license_custom')%>');
          }
        }

        //Authorship validation
        if(!$("input.authorship_checkbox").is(":checked")){
          if($("#AddResource section.authorship input.authorship_author").val() == ""){
            return alert('<%=t('document.validation.author_name')%>');
          }
          if($("#AddResource section.authorship input.authorship_attribution").val() == ""){
            var hasPublicDomainLicense = ($("#AddResource select.resource_license").find(":selected").text() === '<%=t('licenses.public')%>');
            if(!hasPublicDomainLicense){
              return alert('<%=t('document.validation.license_attribution')%>');
            }
          }
        }
        break;
      case "link":
        if ($("#AddResource input[name='"+resource_type+"[url]']").val() == ""){
          return alert("<%= t('link.title3')%>");
        }
        break;
      case "embed":
        if ($("#AddResource input[name='"+resource_type+"[fulltext]']").val() == "") {
          return alert("<%= t('embed.title3')%>");
        }
        break;
      default:
        break;
    }

    //TITLE
    $("#AddResource input[name='"+resource_type+"[title]']").val($(".title").val());
    //DESCRIPTION
    $("#AddResource input[name='"+resource_type+"[description]']").val($(".description").val());
    //TAGS
    var resourceTagList = $("#AddResource .resourceTagList");
    $("#AddResource input[name='"+resource_type+"[tag_list][]']").val(Vish.Utils.convertToTagsArray($(resourceTagList).tagit("tags")));
    //Avatar
    var avatarFileInput = $("#AddResource .new_file_avatar");
    $(avatarFileInput).attr("name",resource_type+"[avatar]");
    var myForm = $("#AddResource form#new_file_only_new_" + resource_type);
    $(avatarFileInput).css("display","none");
    $(avatarFileInput).appendTo(myForm);
    //LANGUAGE
    $("#AddResource input[name='"+resource_type+"[language]']").val($("#AddResource .resource_language").val());

    if(resource_type==="document"){
      //LICENSE
      $("#AddResource input[name='"+resource_type+"[license_id]']").val($("#AddResource .resource_license").val());
      if($("#AddResource section.license select.resource_license").find(":selected").text()==="<%=t("licenses.other")%>"){
        //Custom license
        $("#AddResource input[name='"+resource_type+"[license_custom]']").val($("#AddResource section.license div.license_custom_wrapper input").val());
      }
      //AUTHORSHIP
      $("#AddResource input[name='"+resource_type+"[original_author]']").val($("#AddResource section.authorship input.authorship_author").val());
      $("#AddResource input[name='"+resource_type+"[license_attribution]']").val($("#AddResource section.authorship input.authorship_attribution").val());
    }

    //AGE
    var value1 = $('#AddResource .age-slider').data('slider').getValue()[0];
    var value2 = $('#AddResource .age-slider').data('slider').getValue()[1];
    $('#AddResource input[name="'+resource_type+'[age_min]"]').val(value1);
    $('#AddResource input[name="'+resource_type+'[age_max]"]').val(value2);

    $(this).button('loading');
    //SUBMIT

    $("#AddResource input[value=<%= t('button.save') %>][type='submit'][name='commit'][class='"+resource_type+" hide']").click();
  });

  //Tags
  var resourceTagList = $("#AddResource .resourceTagList");
  var resourceTags = [];

  //Load tags
  $.each($("#AddResource #resourcePreloadTagList li"), function(index, element) {
     resourceTags.push($(element).html());
  });

  if ($(resourceTagList).children().length == 0){
    $(resourceTagList).tagit({
      tagSource: resourceTags,
      sortable: false,
      maxLength: '<%=Vish::Application.config.tagsSettings["maxLength"]%>',
      maxTags: '<%=Vish::Application.config.tagsSettings["maxTags"]%>',
      triggerKeys: <%=raw(Vish::Application.config.tagsSettings["triggerKeys"].to_json)%>,
      watermarkAllowMessage: '<%=t('document.tags.addMessage')%>',
      watermarkDenyMessage: '<%=t('document.tags.limitMessage')%>'
    });
  }

  //File chooser listener
  $("#AddResource #new_file_only_document_file").on('change', function(e){
    try{
      var ext = $(this).val().split(".").pop().toLowerCase();
      var imageFormats = ["jpg","jpeg","png","gif","bmp","svg"];
      if(imageFormats.indexOf(ext)!=-1){
        //Its a image
        enableUploadAvatar(false);
      } else {
        enableUploadAvatar(true);
      }
    } catch(e){
      enableUploadAvatar(true);
    }
  });

  var enableUploadAvatar = function(enable){
    var label = $("#AddResource label.new_file_avatar_label");
    var input = $("#AddResource input.new_file_avatar");
    $(input).prop('disabled', !enable);

    if(enable===true){
      $(label).removeClass("disabled");
      $(label).show();
      $(input).show();
    }else{
      $(label).addClass("disabled");
      $(label).hide();
      $(input).hide();
    }
  };

  //Authorship
  $("#AddResource section.authorship input[type='checkbox']").change(function(){
    var checked = $(this).prop('checked');
    var authorDOM = $(this).parent().find("input.authorship_author");
    var attributionDOM = $(this).parent().find("input.authorship_attribution");

    if(checked){
      $(authorDOM).attr("disabled","disabled");
      $(authorDOM).val($(authorDOM).attr("defaultvalue"));
      $(attributionDOM).attr("disabled","disabled");
      $(attributionDOM).val($(attributionDOM).attr("defaultvalue"));
    } else {
      $(authorDOM).removeAttr("disabled");
      $(authorDOM).val("");
      $(attributionDOM).removeAttr("disabled");
      $(attributionDOM).val("");
    }
  });

  //Collapse events
  $('#AddResource .panel.panel-default').on('shown.bs.collapse', function(e){
    var resourceType = $(this).find(".panel-collapse.collapse").attr("id");

    if(resourceType=="document"){
      //Show authorship fields
      $("#AddResource").find("section.license").show();
      $("#AddResource").find("section.authorship").show();
    } else {
      //Hide authorship fields
      $("#AddResource").find("section.license").hide();
      $("#AddResource").find("section.authorship").hide();
    }
  });

  //Custom license listener
  $("#AddResource section.license select.resource_license").change(function(event){
    if($(this).find(":selected").text()==="<%=t("licenses.other")%>"){
      if(!$("#AddResource section.license div.license_custom_wrapper").is(":visible")){
        $("#AddResource section.license div.license_custom_wrapper").show();
      }
    } else {
      if($("#AddResource section.license div.license_custom_wrapper").is(":visible")){
        $("#AddResource section.license div.license_custom_wrapper").hide();
      }
    }
  });

<%end%>
